package cn.fl.custpay.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.custpay.condition.PayInsRcvAccQC;
import cn.fl.custpay.service.IPayInsRcvAccService;
import cn.fl.custpay.vo.PayInsRcvAccVO;
import cn.fl.project.vo.PrjLinkManVO;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.vo.BankAccInfoVO;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.riskctrl.vo.RskCtrlMVO;
import cn.fl.system.constant.SysLogConstant;
import fl.constant.facade.framework.constant.DictionaryConstant;
import fl.ref.fncprjbscinfo.condition.FncPrjBscInfoQueryCondition;
import fl.ref.fncprjbscinfo.service.IFncPrjBscInfoApiService;
import fl.ref.fribaseinfo.condition.BankAccInfoQueryCondition;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.fribaseinfo.constant.FriBaseInfoConstant;
import fl.ref.fribaseinfo.dto.BankAccInfoDTO;
import fl.ref.fribaseinfo.service.IBankAccInfoApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import cn.fl.framework.base.context.CurrentThreadContext;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;

/**
 * @Description: 融资机构资管收款账户三方支付商户号表（客户还款） 控制层
 */
@Controller
@RequestMapping("/custpay/payInsRcvAcc")
public class PayInsRcvAccController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PayInsRcvAccController.class);

	/**
	 * PayInsRcvAcc 服务层BEAN
	 */
	@Autowired
	private IPayInsRcvAccService payInsRcvAccService;

	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	/**
	 * 再融资服务
	 */
	@Autowired
	private IFriBaseInfoService friBaseInfoService;

	@Autowired
	private IFncPrjBscInfoApiService fncPrjBscInfoApiService;

	/**
	 * 融资机构银行帐号信息
	 */
	@Autowired
	private IBankAccInfoApiService bankAccInfoApiService;


	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("custpay/payInsRcvAcc/list");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		//系统编码
		String payChlCd = PropertiesCacheUtils.getProperty(DictionaryConstant.PAY_CHL_CD);
		List<KeyValueVO> list = this.sysDictionaryApiService.getKvList(payChlCd, CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
		view.addObject("payChlCdList", list);
		//交易类型
		String transTypCd = PropertiesCacheUtils.getProperty(DictionaryConstant.TRANS_TYP_CD);
		List<KeyValueVO> transTypCdlist = this.sysDictionaryApiService.getKvList(transTypCd, CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd());
		view.addObject("transTypCdlist", transTypCdlist);
		return view;
	}

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/getBankAcc.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getBankAcc(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getBankAcc", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
//			//1、获取金融机构信息 id为金融机构编号
//			FriBaseInfoVO friBaseInfoVO  =this.friBaseInfoService.selectById(Long.valueOf(id), CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
//			//2、获取机构下的银行信息
//			List<BankAccInfoVO> bilist=friBaseInfoVO.getBankAccInfoVOs();
			BankAccInfoQueryCondition bankAccInfoQC = new BankAccInfoQueryCondition();
			bankAccInfoQC.setFundRasInsId(Long.parseLong(id));
			bankAccInfoQC.setAccTypCd("2");
			bankAccInfoQC.setSysCd(CurrentThreadContext.getCurrentSysCd());
			bankAccInfoQC.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			List<BankAccInfoDTO> banklst = this.bankAccInfoApiService.searchList(bankAccInfoQC);
			result.setData(banklst);
			BaseLogUtils.info(logger, "getBankAcc", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getBankAcc", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getBankAcc", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 机构列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initFundList.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object initFundList(HttpServletRequest request, HttpServletResponse response) {
		String fundRasInsNm = request.getParameter("fundRasInsNm");
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		FriBaseInfoQueryCondition qc = new FriBaseInfoQueryCondition();
		if (StringUtils.isNotEmpty(fundRasInsNm)) {
			qc.setFundRasInsNm(fundRasInsNm);//金融机构名称  模糊查询
		}
		qc.setInsSts(FriBaseInfoConstant.FRI_BASE_INFO_INS_STS_PASS);
//		qc.setInsUseCd("2");
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		page.setCondition(qc);
		Pager pager = this.friBaseInfoService.searchListPage(page);
		List<PrjLinkManVO> list = (List<PrjLinkManVO>) pager.getResultList();
		ListPageVO<PrjLinkManVO> listPage = new ListPageVO<PrjLinkManVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 项目列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initPrjList.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object initPrjList(HttpServletRequest request, HttpServletResponse response) {
		String fncprjnm = request.getParameter("fncprjnm");
        String fncinsid = request.getParameter("fncinsid");
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		FncPrjBscInfoQueryCondition qc = new FncPrjBscInfoQueryCondition();
		if (StringUtils.isNotEmpty(fncprjnm)) {
			qc.setFncprjnm(fncprjnm);//金融机构名称  模糊查询
		}
        if (StringUtils.isNotEmpty(fncinsid)) {
            qc.setFncinsid(fncinsid);//金融机构ID
        }
		page.setCondition(qc);
		Pager pager = this.fncPrjBscInfoApiService.searchListPage(page);
		List<PrjLinkManVO> list = (List<PrjLinkManVO>) pager.getResultList();
		ListPageVO<PrjLinkManVO> listPage = new ListPageVO<PrjLinkManVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("riskctrl/payInsRcvAcc/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String insNm = request.getParameter("insNm");
		String payChlCd = request.getParameter("payChlCd");
		String transTypCd = request.getParameter("transTypCd");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		PayInsRcvAccQC qc = new PayInsRcvAccQC();
		if (StringUtils.isNotEmpty(insNm)) {
			qc.setInsNm(insNm);
		}
		if (StringUtils.isNotEmpty(payChlCd)) {
			qc.setPayChlCd(payChlCd);
		}
		if (StringUtils.isNotEmpty(transTypCd)) {
			qc.setTransTypCd(transTypCd);
		}
		page.setCondition(qc);
		Pager pager = this.payInsRcvAccService.searchListPage(page);
		List<PayInsRcvAccVO> list = (List<PayInsRcvAccVO>) pager.getResultList();
		ListPageVO<PayInsRcvAccVO> listPage = new ListPageVO<PayInsRcvAccVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.GET })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.payInsRcvAccService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			PayInsRcvAccVO vo = this.payInsRcvAccService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String insNm = request.getParameter("insNm");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		PayInsRcvAccVO entity = null;
		try {
			entity = new PayInsRcvAccVO();
			//TODO ADD PARAM
			entity = this.getRequestParamForAdd(request);
			Long id = this.payInsRcvAccService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		PayInsRcvAccVO entity = null;
		try {
			entity = new PayInsRcvAccVO();
			entity = this.getRequestParamForModify(request);
			entity.setId(Long.valueOf(id));
			//TODO ADD PARAM
			boolean success = this.payInsRcvAccService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	private PayInsRcvAccVO getRequestParamForAdd(HttpServletRequest request)throws BaseException{
		PayInsRcvAccVO payInsRcvAccVO = this.getRequestParamForRsk(request);
		payInsRcvAccVO.setCrtTm(new Date());
		payInsRcvAccVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		return payInsRcvAccVO;
	}

	private PayInsRcvAccVO getRequestParamForModify(HttpServletRequest request)throws BaseException{
		PayInsRcvAccVO payInsRcvAccVO = this.getRequestParamForRsk(request);
		payInsRcvAccVO.setMdfTm(new Date());
		payInsRcvAccVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		return payInsRcvAccVO;
	}

	private PayInsRcvAccVO getRequestParamForRsk(HttpServletRequest request)throws BaseException{
		String insNm = request.getParameter("insNm");//机构名称
		String insId = request.getParameter("insId");//机构id
        String prjId = request.getParameter("prjId");//项目id
		String insAccNoId = request.getParameter("insAccNoId");//融资机构账户ID
		String payChlCd = request.getParameter("payChlCd");//支付平台代码
		String transTypCd = request.getParameter("transTypCd");//交易类型
		String payChlBizNo = request.getParameter("payChlBizNo");//支付平台商户号
		String payKey = request.getParameter("payKey");//支付秘钥

		PayInsRcvAccVO payInsRcvAccVO = new PayInsRcvAccVO();
		if (StringUtils.isNotEmpty(insNm)) {
			payInsRcvAccVO.setInsNm(insNm.trim());
		}
		if (StringUtils.isNotEmpty(insId)) {
			payInsRcvAccVO.setInsId(Long.valueOf(insId.trim()));
		}
        if (StringUtils.isNotEmpty(prjId)) {
            payInsRcvAccVO.setPrjId(Long.valueOf(prjId.trim()));
        }
		if (StringUtils.isNotEmpty(insAccNoId)) {
			payInsRcvAccVO.setInsAccNoId(insAccNoId.trim());
		}
		if (StringUtils.isNotEmpty(payChlCd)) {
			payInsRcvAccVO.setPayChlCd(Long.valueOf(payChlCd.trim()));
		}
		if (StringUtils.isNotEmpty(transTypCd)) {
			payInsRcvAccVO.setTransTypCd(transTypCd.trim());
		}
		if (StringUtils.isNotEmpty(payChlBizNo)) {
			payInsRcvAccVO.setPayChlBizNo(payChlBizNo.trim());
		}
		if (StringUtils.isNotEmpty(payKey)) {
			payInsRcvAccVO.setPayKey(payKey);
		}
		return payInsRcvAccVO;
	}
}

